//
//  EmosionTextView.swift
//  表情键盘
//
//  Created by mac on 15/5/24.
//  Copyright (c) 2015年 mac. All rights reserved.
//

import UIKit

class EmosionTextView: UITextView {

    //--------------step<22>---实现图文混盘----------------------------------------------------------
   func emosionInsert(emosion: Emotions)
    {
        
        if emosion.chs != nil{
            
            let height = font.lineHeight
            let attrStr = EmotionAttachment.NSAttributedStringWithImagePath(emosion, height: height)
            ///Step: <24> 把文本添加到textView
            var strM = NSMutableAttributedString(attributedString: attributedText)
            //        strM.appendAttributedString(attrStr)
            strM.replaceCharactersInRange(selectedRange, withAttributedString: attrStr) ///Step: <26>实现光标和插入位置对应
            var selectrange = selectedRange  ///Step: <27> 实现光标不乱跳
            strM.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, strM.length)) ///Step: <29> 使得插入图片风格和被插入统一
            attributedText = strM
            selectedRange = NSMakeRange(selectrange.location+1, 0) ///Step: <27>
        }
        else if emosion.emojiStr != nil
        {
            replaceRange(selectedTextRange!, withText: emosion.emojiStr!) ///Step: <30> 实现插入国际通用表情在
        }
        
        //        println("======1111===============\(textView.attributedText)==========3333==========================")
        //        println("*****123***************************\(textView.text)*************124***********")
        
    }
    

    //返回完整文本
    func fulltext() -> String
    {
        
        let yaoye = attributedText
        var yaoye2 = String()
        attributedText.enumerateAttributesInRange(NSMakeRange(0, yaoye.length), options: NSAttributedStringEnumerationOptions(0)) { (dict, range, _) -> Void in
            
            println("---\(dict)------+++\(range)---------------")
            
            //--------------step<31>-------------拿到自定义附件对象的我们输人的内容 文字和图片------------------------------------------------
            if let attachment = dict["NSAttachment"] as? EmotionAttachment
            {
                println("有图片")
                yaoye2 += attachment.chs!
            }
            else
            {
                let str = (yaoye.string as NSString).substringWithRange(range)
                println("======\(str)")
                yaoye2 += str
            }
            
        }
        println(yaoye2) ///Step: <31>
        return yaoye2
    
    }

}
